<template>
  <div class="appointment-management">
    <div class="page-header">
      <h2 class="page-title">服务预约管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加预约
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="老人姓名">
          <el-select v-model="searchForm.elderlyId" placeholder="请选择老人" clearable filterable style="width: 200px">
            <el-option
              v-for="elderly in elderlyOptions"
              :key="elderly.id"
              :label="elderly.name"
              :value="elderly.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select v-model="searchForm.serviceType" placeholder="请选择服务类型" clearable style="width: 150px">
            <el-option label="体检" value="physical_exam" />
            <el-option label="护理" value="nursing" />
            <el-option label="送餐" value="meal_delivery" />
            <el-option label="清洁" value="cleaning" />
            <el-option label="陪伴" value="companionship" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table :data="appointmentList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="elderlyName" label="老人姓名" />
        <el-table-column prop="serviceType" label="服务类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getServiceTypeColor(row.serviceType)">
              {{ getServiceTypeLabel(row.serviceType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentDate" label="预约日期" width="120" />
        <el-table-column prop="appointmentTime" label="预约时间" width="120" />
        <el-table-column prop="duration" label="预计时长" width="100" />
        <el-table-column prop="fee" label="费用" width="100">
          <template #default="{ row }">
            <span v-if="row.fee">¥{{ row.fee }}</span>
            <span v-else class="text-gray-400">未设置</span>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="staffName" label="服务人员" />
        <el-table-column prop="bookerName" label="预约人" width="120">
          <template #default="{ row }">
            <span v-if="row.bookerName">{{ row.bookerName }}</span>
            <span v-else class="text-gray-400">本人</span>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评价" width="120">
          <template #default="{ row }">
            <el-rate 
              v-if="row.rating" 
              :model-value="row.rating" 
              disabled 
              show-score
              text-color="#ff9900"
              size="small"
            />
            <span v-else class="text-gray-400">未评价</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === 'pending' ? 'success' : 'info'" 
              @click="handleStatusChange(row)"
              :disabled="row.status === 'completed' || row.status === 'cancelled'"
            >
              {{ getActionText(row.status) }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="老人" prop="elderlyId">
              <el-select v-model="formData.elderlyId" placeholder="请选择老人" filterable>
                <el-option
                  v-for="elderly in elderlyOptions"
                  :key="elderly.id"
                  :label="elderly.name"
                  :value="elderly.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务类型" prop="serviceType">
              <el-select v-model="formData.serviceType" placeholder="请选择服务类型">
                <el-option label="体检" value="physical_exam" />
                <el-option label="护理" value="nursing" />
                <el-option label="送餐" value="meal_delivery" />
                <el-option label="清洁" value="cleaning" />
                <el-option label="陪伴" value="companionship" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约日期" prop="appointmentDate">
              <el-date-picker
                v-model="formData.appointmentDate"
                type="date"
                placeholder="选择预约日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时间" prop="appointmentTime">
              <el-time-picker
                v-model="formData.appointmentTime"
                placeholder="选择预约时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计时长" prop="duration">
              <el-input v-model="formData.duration" placeholder="如：2小时" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务人员" prop="staffId">
              <el-select v-model="formData.staffId" placeholder="请选择服务人员" filterable>
                <el-option
                  v-for="staff in staffOptions"
                  :key="staff.id"
                  :label="staff.name"
                  :value="staff.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务费用">
              <el-input-number v-model="formData.fee" :min="0" :precision="2" placeholder="服务费用" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度">
              <el-select v-model="formData.priority" placeholder="请选择紧急程度">
                <el-option label="低" value="LOW" />
                <el-option label="普通" value="NORMAL" />
                <el-option label="高" value="HIGH" />
                <el-option label="紧急" value="URGENT" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约人姓名">
              <el-input v-model="formData.bookerName" placeholder="如果非本人预约请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约人电话">
              <el-input v-model="formData.bookerPhone" placeholder="预约人联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="服务地址" prop="address">
          <el-input v-model="formData.address" type="textarea" rows="2" />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input v-model="formData.notes" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="预约详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="老人姓名">{{ viewData.elderlyName }}</el-descriptions-item>
        <el-descriptions-item label="服务类型">
          <el-tag :type="getServiceTypeColor(viewData.serviceType)">
            {{ getServiceTypeLabel(viewData.serviceType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="预约日期">{{ viewData.appointmentDate }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ viewData.appointmentTime }}</el-descriptions-item>
        <el-descriptions-item label="预计时长">{{ viewData.duration }}</el-descriptions-item>
        <el-descriptions-item label="服务费用">
          <span v-if="viewData.fee">¥{{ viewData.fee }}</span>
          <span v-else class="text-gray-400">未设置</span>
        </el-descriptions-item>
        <el-descriptions-item label="紧急程度">
          <el-tag :type="getPriorityColor(viewData.priority)">
            {{ getPriorityLabel(viewData.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(viewData.status)">
            {{ getStatusLabel(viewData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="服务人员">{{ viewData.staffName }}</el-descriptions-item>
        <el-descriptions-item label="预约人">
          <span v-if="viewData.bookerName">{{ viewData.bookerName }}</span>
          <span v-else class="text-gray-400">本人</span>
        </el-descriptions-item>
        <el-descriptions-item label="预约人电话">
          <span v-if="viewData.bookerPhone">{{ viewData.bookerPhone }}</span>
          <span v-else class="text-gray-400">无</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="服务地址" :span="2">{{ viewData.address }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.notes || '无' }}</el-descriptions-item>
        <el-descriptions-item label="评价等级" v-if="viewData.rating">
          <el-rate 
            :model-value="viewData.rating" 
            disabled 
            show-score
            text-color="#ff9900"
          />
        </el-descriptions-item>
        <el-descriptions-item label="评价内容" :span="2" v-if="viewData.reviewContent">
          {{ viewData.reviewContent }}
        </el-descriptions-item>
        <el-descriptions-item label="取消原因" :span="2" v-if="viewData.cancelReason">
          {{ viewData.cancelReason }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

// 响应式数据
const loading = ref(false)
const appointmentList = ref<any[]>([])
const elderlyOptions = ref<any[]>([])
const staffOptions = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  elderlyId: '',
  serviceType: '',
  status: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const formRef = ref()
const formData = reactive({
  id: null,
  elderlyId: '',
  serviceType: '',
  appointmentDate: '',
  appointmentTime: '',
  duration: '',
  staffId: '',
  address: '',
  notes: '',
  fee: 0,
  priority: 'NORMAL',
  bookerName: '',
  bookerPhone: ''
})

// 查看数据
const viewData = ref<any>({})

// 表单验证规则
const formRules = {
  elderlyId: [
    { required: true, message: '请选择老人', trigger: 'change' }
  ],
  serviceType: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入预计时长', trigger: 'blur' }
  ],
  staffId: [
    { required: true, message: '请选择服务人员', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入服务地址', trigger: 'blur' }
  ]
}

// 获取服务类型标签
const getServiceTypeLabel = (type: string) => {
  const typeMap: { [key: string]: string } = {
    physical_exam: '体检',
    nursing: '护理',
    meal_delivery: '送餐',
    cleaning: '清洁',
    companionship: '陪伴'
  }
  return typeMap[type] || type
}

// 获取服务类型颜色
const getServiceTypeColor = (type: string) => {
  const colorMap: { [key: string]: string } = {
    physical_exam: 'success',
    nursing: 'primary',
    meal_delivery: 'warning',
    cleaning: 'info',
    companionship: 'danger'
  }
  return colorMap[type] || 'default'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const statusMap: { [key: string]: string } = {
    PENDING: '待确认',
    pending: '待确认',
    CONFIRMED: '已确认',
    confirmed: '已确认',
    IN_PROGRESS: '进行中',
    in_progress: '进行中',
    COMPLETED: '已完成',
    completed: '已完成',
    CANCELLED: '已取消',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: { [key: string]: string } = {
    PENDING: 'warning',
    pending: 'warning',
    CONFIRMED: 'primary',
    confirmed: 'primary',
    IN_PROGRESS: 'success',
    in_progress: 'success',
    COMPLETED: 'success',
    completed: 'success',
    CANCELLED: 'danger',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取操作按钮文本
const getActionText = (status: string) => {
  const actionMap: { [key: string]: string } = {
    PENDING: '确认',
    pending: '确认',
    CONFIRMED: '开始',
    confirmed: '开始',
    IN_PROGRESS: '完成',
    in_progress: '完成'
  }
  return actionMap[status] || '操作'
}

// 获取优先级标签
const getPriorityLabel = (priority: string) => {
  const priorityMap: { [key: string]: string } = {
    LOW: '低',
    low: '低',
    NORMAL: '普通',
    normal: '普通',
    HIGH: '高',
    high: '高',
    URGENT: '紧急',
    urgent: '紧急'
  }
  return priorityMap[priority] || '普通'
}

// 获取优先级颜色
const getPriorityColor = (priority: string) => {
  const colorMap: { [key: string]: string } = {
    LOW: 'info',
    low: 'info',
    NORMAL: 'success',
    normal: 'success',
    HIGH: 'warning',
    high: 'warning',
    URGENT: 'danger',
    urgent: 'danger'
  }
  return colorMap[priority] || 'success'
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期
const formatDate = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN')
}

// 格式化时间
const formatTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', (currentPage.value - 1).toString())
    params.append('size', pageSize.value.toString())
    
    // 添加搜索条件
    if (searchForm.elderlyId) {
      params.append('elderlyId', searchForm.elderlyId.toString())
    }
    if (searchForm.serviceType) {
      params.append('serviceType', searchForm.serviceType)
    }
    if (searchForm.status) {
      params.append('status', searchForm.status.toUpperCase())
    }
    
    const response = await fetch(`${API_BASE_URL}/appointments?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('获取预约列表失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 处理数据，添加老人姓名和员工姓名
      const appointmentsWithNames = await Promise.all(result.data.content.map(async (appointment: any) => {
        const elderlyName = await getElderlyName(appointment.elderlyId)
        const staffName = appointment.staffId ? await getStaffName(appointment.staffId) : '未分配'
        
        return {
          id: appointment.id,
          elderlyId: appointment.elderlyId,
          elderlyName,
          serviceType: appointment.serviceType,
          appointmentDate: formatDate(appointment.appointmentTime),
          appointmentTime: formatTime(appointment.appointmentTime),
          duration: calculateDuration(appointment.appointmentTime, appointment.endTime),
          status: appointment.status,
          staffId: appointment.staffId,
          staffName,
          address: appointment.serviceAddress || '',
          notes: appointment.notes || '',
          createTime: formatDateTime(appointment.createTime),
          fee: appointment.fee,
          priority: appointment.priority || 'NORMAL',
          bookerName: appointment.bookerName || '',
          bookerPhone: appointment.bookerPhone || '',
          rating: appointment.rating,
          reviewContent: appointment.reviewContent || '',
          cancelReason: appointment.cancelReason || '',
          appointmentTimeRaw: appointment.appointmentTime,
          endTime: appointment.endTime
        }
      }))
      
      appointmentList.value = appointmentsWithNames
      total.value = result.data.totalElements
    } else {
      ElMessage.error(result.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('加载预约列表失败:', error)
    ElMessage.error('加载预约列表失败')
  } finally {
    loading.value = false
  }
}

// 获取老人姓名
const getElderlyName = async (elderlyId: number) => {
  try {
    const response = await fetch(`${API_BASE_URL}/elderly/${elderlyId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        return result.data.name
      }
    }
    return `老人${elderlyId}`
  } catch (error) {
    return `老人${elderlyId}`
  }
}

// 获取员工姓名
const getStaffName = async (staffId: number) => {
  try {
    const response = await fetch(`${API_BASE_URL}/staff/${staffId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        return result.data.name
      }
    }
    return `员工${staffId}`
  } catch (error) {
    return `员工${staffId}`
  }
}

// 计算时长
const calculateDuration = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) return '未设置'
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diffMs = end.getTime() - start.getTime()
  const diffHours = Math.round(diffMs / (1000 * 60 * 60) * 10) / 10
  
  if (diffHours < 1) {
    const diffMinutes = Math.round(diffMs / (1000 * 60))
    return `${diffMinutes}分钟`
  }
  
  return `${diffHours}小时`
}

// 加载选项数据
const loadOptions = async () => {
  await Promise.all([
    loadElderlyOptions(),
    loadStaffOptions()
  ])
}

// 加载老人选项
const loadElderlyOptions = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/elderly?page=0&size=100`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        elderlyOptions.value = result.data.content.map((elderly: any) => ({
          id: elderly.id,
          name: elderly.name
        }))
      }
    }
  } catch (error) {
    console.error('加载老人选项失败:', error)
  }
}

// 加载员工选项
const loadStaffOptions = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/staff?page=0&size=100`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        staffOptions.value = result.data.content.map((staff: any) => ({
          id: staff.id,
          name: staff.name
        }))
      }
    }
  } catch (error) {
    console.error('加载员工选项失败:', error)
  }
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1 // 重置到第一页
  await loadData()
}

// 重置搜索
const resetSearch = async () => {
  Object.assign(searchForm, {
    elderlyId: '',
    serviceType: '',
    status: ''
  })
  currentPage.value = 1
  await loadData()
}

// 添加
const handleAdd = () => {
  dialogTitle.value = '添加预约'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑预约'
  isEdit.value = true
  
  // 处理日期时间数据
  const appointmentDateTime = new Date(row.appointmentTimeRaw)
  
  Object.assign(formData, {
    id: row.id,
    elderlyId: row.elderlyId,
    serviceType: row.serviceType,
    appointmentDate: appointmentDateTime,
    appointmentTime: appointmentDateTime,
    duration: row.duration,
    staffId: row.staffId,
    address: row.address,
    notes: row.notes,
    fee: row.fee,
    priority: row.priority,
    bookerName: row.bookerName,
    bookerPhone: row.bookerPhone
  })
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  viewData.value = row
  viewDialogVisible.value = true
}

// 状态变更
const handleStatusChange = async (row: any) => {
  let action = ''
  let message = ''
  
  if (row.status === 'PENDING' || row.status === 'pending') {
    action = 'confirm'
    message = '确认预约'
  } else if (row.status === 'CONFIRMED' || row.status === 'confirmed') {
    action = 'start'
    message = '开始服务'
  } else if (row.status === 'IN_PROGRESS' || row.status === 'in_progress') {
    action = 'complete'
    message = '完成服务'
  }
  
  try {
    await ElMessageBox.confirm(`确定要${message}吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    const response = await fetch(`${API_BASE_URL}/appointments/${row.id}/${action}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error(`${message}失败`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success(`${message}成功`)
      await loadData()
    } else {
      ElMessage.error(result.message || `${message}失败`)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error(`${message}失败:`, error)
      ElMessage.error(`${message}失败`)
    }
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条预约记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await fetch(`${API_BASE_URL}/appointments/${row.id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('删除失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('删除成功')
      await loadData()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除预约失败:', error)
      ElMessage.error('删除预约失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    // 准备提交数据
    const appointmentDateTime = new Date(formData.appointmentDate)
    const timeDate = new Date(formData.appointmentTime)
    
    // 合并日期和时间
    appointmentDateTime.setHours(timeDate.getHours())
    appointmentDateTime.setMinutes(timeDate.getMinutes())
    
    // 计算结束时间（根据时长）
    const endDateTime = new Date(appointmentDateTime)
    const durationMatch = formData.duration.match(/(\d+\.?\d*)/);
    const durationHours = durationMatch ? parseFloat(durationMatch[1]) : 1;
    endDateTime.setHours(endDateTime.getHours() + durationHours)
    
    const submitData = {
      elderlyId: formData.elderlyId,
      serviceType: formData.serviceType,
      appointmentTime: appointmentDateTime.toISOString(),
      endTime: endDateTime.toISOString(),
      staffId: formData.staffId || null,
      serviceAddress: formData.address,
      notes: formData.notes || '',
      status: 'PENDING',
      fee: formData.fee,
      priority: formData.priority,
      bookerName: formData.bookerName,
      bookerPhone: formData.bookerPhone
    }
    
    let response
    if (isEdit.value) {
      // 更新
      response = await fetch(`${API_BASE_URL}/appointments/${formData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(submitData)
      })
    } else {
      // 创建
      response = await fetch(`${API_BASE_URL}/appointments`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(submitData)
      })
    }
    
    if (!response.ok) {
      throw new Error(isEdit.value ? '更新失败' : '添加失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      dialogVisible.value = false
      await loadData()
    } else {
      ElMessage.error(result.message || (isEdit.value ? '更新失败' : '添加失败'))
    }
  } catch (error: any) {
    console.error('提交预约失败:', error)
    ElMessage.error(isEdit.value ? '更新预约失败' : '添加预约失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    elderlyId: '',
    serviceType: '',
    appointmentDate: '',
    appointmentTime: '',
    duration: '',
    staffId: '',
    address: '',
    notes: '',
    fee: 0,
    priority: 'NORMAL',
    bookerName: '',
    bookerPhone: ''
  })
}

// 分页
const handleSizeChange = async (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  await loadData()
}

const handleCurrentChange = async (val: number) => {
  currentPage.value = val
  await loadData()
}

onMounted(async () => {
  await loadOptions()
  await loadData()
})
</script>

<style scoped>
.appointment-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 